<?php

namespace app\ask\controller;

use think\Controller;

class Comment extends Controller
{
    protected $BusinessModel;
    protected $PostModel;
    protected $CommentModel;

    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->PostModel = model('post.Post');
        $this->CommentModel = model('post.Comment');
    }

    public function index()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page', 1, 'intval');
            $limit = $this->request->param('limit', 10, 'intval');
            $postid = $this->request->param('postid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');
            $pid = $this->request->param('pid', 0, 'trim');

            $offset = ($page - 1) * $limit;

            $post = $this->PostModel->find($postid);

            if (!$post) {
                $this->error('暂无帖子信息');
                exit;
            }

            $where = ['postid' => $postid];

            if ($busid) {
                // $where['busid'] = $busid;
            }

            if ($pid !== -1) {
                $where['pid'] = $pid;
            }

            $total = $this->CommentModel
                ->where($where)
                ->count();

            $list = $this->CommentModel
                ->with(['business'])
                ->where($where)
                ->order(['pid asc', 'level asc', 'id asc'])
                ->limit($offset, $limit)
                ->select();

            // var_dump( $this->CommentModel->getLastSql());exit;

            if (empty($list)) {
                $this->error('暂无评论');
                exit;
            }

            foreach ($list as &$item) {
                $item = $item->toArray();

                $item['business'] = filter_property($item['business'], ['id', 'avatar_text', 'nickname']);
                if ($item['reply_business']) $item['reply_business'] = filter_property($item['reply_business'], ['id', 'avatar_text', 'nickname']);
            }

            $this->success('返回评论列表', null, ['list' => $list, 'total' => $total]);
            exit;
        }
    }

    // 点赞
    public function like()
    {
        $id = $this->request->param('id', 0, 'trim');
        $postid = $this->request->param('postid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');

        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $post = $this->PostModel->find($postid);

        if (!$post) {
            $this->error('帖子不存在');
            exit;
        }

        $comment = $this->CommentModel->find($id);

        if (!$comment) {
            $this->error('评论不存在');
            exit;
        }

        $data = [
            'id' => $comment['id'],
        ];

        $like_list = $comment['like_list'];

        //判断元素是否在数组内
        if (in_array($busid, $like_list)) {
            //如果有找到就说明点个赞，就是要取消点赞
            $index = array_search($busid, $like_list);
            unset($like_list[$index]);
        } else {
            $like_list[] = $busid;
        }

        if (empty($like_list)) {
            $data['like'] = NULL;
        } else {
            $data['like'] = implode(',', $like_list);
        }

        //更新
        $result = $this->CommentModel->isUpdate(true)->save($data);

        if ($result === false) {
            $this->error('发生错误');
            exit;
        } else {
            $this->success('ok');
            exit;
        }
    }

    // 添加评论
    public function add()
    {
        $postid = $this->request->param('postid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');
        $pid = $this->request->param('pid', 0, 'trim');
        $replyid = $this->request->param('replyid', 0, 'trim');
        $content = $this->request->param('content', '', 'trim');

        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $post = $this->PostModel->find($postid);

        if (!$post) {
            $this->error('帖子不存在');
            exit;
        }

        $data = [
            'postid' => $postid,
            'busid' => $busid,
            'content' => $content,
        ];

        if ($pid) {
            $comment = $this->CommentModel->find($pid);

            if (!$comment) {
                $this->error('父级评论不存在');
                exit;
            }

            $data['pid'] = $pid;
        }

        if ($replyid) {
            $comment = $this->CommentModel->find($replyid);

            if (!$comment) {
                $this->error('回复评论不存在');
                exit;
            }

            $data['replyid'] = $replyid;
        }

        $res = $this->CommentModel->save($data);

        if ($res === false) {
            $this->error('评论失败');
            exit;
        } else {
            $this->success('评论成功');
            exit;
        }
    }

    // 删除评论 
    public function del()
    {
        $postid = $this->request->param('postid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');
        $commentid = $this->request->param('commentid', 0, 'trim');

        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $post = $this->PostModel->find($postid);

        if (!$post) {
            $this->error('帖子不存在');
            exit;
        }

        $comment = $this->CommentModel->find($commentid);

        if (!$comment) {
            $this->error('评论不存在');
            exit;
        }

        // 判断是否为帖子作者或者是发评论的用户
        if ($business['id'] !== $post['busid'] && $business['id'] !== $comment['busid']) {
            $this->error('非法操作');
            exit;
        }

        $subIds = $this->CommentModel->subIds($commentid);

        $ids = array_merge([$commentid], $subIds);


        $res = $this->CommentModel->where('id', 'in', $ids)->delete();

        if ($res === false) {
            $this->error('删除失败');
            exit;
        } else {
            $this->success('删除成功');
            exit;
        }
    }

    // 采纳
    public function accept()
    {
        $postid = $this->request->param('postid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');
        $commentid = $this->request->param('commentid', 0, 'trim');

        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $post = $this->PostModel->find($postid);

        if (!$post) {
            $this->error('帖子不存在');
            exit;
        }

        if ($post['status'] === '1') {
            $this->error('该帖子已经解决，不能采纳了');
            exit;
        }

        $comment = $this->CommentModel->find($commentid);

        if (!$comment) {
            $this->error('评论不存在');
            exit;
        }

        // 判断是否为帖子作者
        if ($business['id'] !== $post['busid']) {
            $this->error('非法操作');
            exit;
        }

        // 采纳人信息
        $acceptInfo = $this->BusinessModel->find($comment['busid']);

        if (empty($acceptInfo)) {
            $this->error('未知采纳人');
            exit;
        }

        // 开始事务
        $this->PostModel->startTrans();
        $this->BusinessModel->startTrans();

        // 修改帖子状态
        $postData = [
            'id'                => $postid,
            'status'            => 1,
            'accept'            => $acceptInfo['id'],
            'accept_comment_id' => $commentid
        ];

        $postRes = $this->PostModel->isUpdate(true)->save($postData);

        if ($postRes === false) {
            $this->error($this->PostModel->getError());
            exit;
        }

        // 更新采纳人积分
        $newPoint = bcadd($acceptInfo['point'] ?? 0, $post['point']);

        $acceptData = [
            'id'    => $acceptInfo['id'],
            'point' => $newPoint,
        ];

        $acceptRes = $this->BusinessModel->isUpdate(true)->save($acceptData);

        if ($acceptRes === false) {
            $this->PostModel->rollback();
            $this->error($this->BusinessModel->getError());
            exit;
        }

        if ($postRes === false || $acceptRes === false) {
            $this->PostModel->rollback();
            $this->BusinessModel->rollback();
            $this->error('采纳失败');
            exit;
        } else {
            $this->BusinessModel->commit();
            $this->PostModel->commit();
            $this->success('采纳成功');
            exit;
        }
    }

    // 评论列表
    public function list()
    {
        $page = $this->request->param('page', 1, 'intval');
        $limit = $this->request->param('limit', 10, 'intval');
        $busid = $this->request->param('busid', 0, 'trim');

        $offset = ($page - 1) * $limit;

        $where = [];

        if ($busid) {
            $where['busid'] = $busid;
        }

        $total = $this->CommentModel
            ->where($where)
            ->count();

        $list = $this->CommentModel
            ->with(['business'])
            ->where($where)
            ->order(['id desc'])
            ->limit($offset, $limit)
            ->select();

        if (empty($list)) {
            $this->success('暂无评论', null, ['list' => [], 'total' => 0]);
            exit;
        }

        foreach ($list as &$item) {
            $item = $item->toArray();

            $item['business'] = filter_property($item['business'], ['id', 'avatar_text', 'nickname']);
            if ($item['reply_business']) $item['reply_business'] = filter_property($item['reply_business'], ['id', 'avatar_text', 'nickname']);
        }

        $this->success('返回评论列表', null, ['list' => $list, 'total' => $total]);
        exit;
    }
}
